//
//  TranRecordView.swift
//  ptbuy
//
//  Created by MyMac on 2024/12/3.
//

import SwiftUI
import CoreData
import AVKit
import AVFoundation


//交易记录
struct TranRecordView: View {
    
    @Binding var tranRecord:Bool
    
    @Environment(\.managedObjectContext) private var viewContext
    @EnvironmentObject var appDelegate: AppDelegate // 引用 AppDelegate
    
    @State private var totalProduct:Int16 = 0
    @State private var totalPrice:Int64 = 0
    @State private var isProgressLoading:Bool = false
    
    @State private var isScreen:Bool = false//筛选框
    @State private var screenName:String = ""//筛选框
    @State private var screenPhone:String = ""//筛选框
    @State private var screenAgentName:String = ""//筛选框
    
    @State var exportRecord:Bool = false//查看导出记录
    @State var isDel:Bool = false
    
    @State private var exportFail:Bool = false//导出失败提示
    @State private var navigateToDetail:Bool = false
    
    @FetchRequest(
        entity: Client.entity(),
        sortDescriptors: [NSSortDescriptor(
            keyPath: \Client.myorder,
            ascending: false
        )],
        animation: .default
    ) private var client: FetchedResults<Client>
    
    var body: some View {
        NavigationView {
            VStack{
                Divider()
                if isScreen{
                    VStack{
                        HStack{
                            Text("客户姓名") .font(.system(size: 15))
                            Spacer()
                            TextField("客户名称",text: $screenName).minimumScaleFactor(0.3)
                                .multilineTextAlignment(.center)
                                .minimumScaleFactor(0.3).overlay(
                                    Rectangle()
                                        .frame(height: 1)
                                        .foregroundColor(Color.black)
                                        .padding([.top])
                                )
                                .cornerRadius(8).font(.system(size: 15))
                        }.padding([.leading,.trailing],30)
                        Divider()
                        HStack{
                            Text("客户电话") .font(.system(size: 15))
                            Spacer()
                            TextField("客户电话",text: $screenPhone).keyboardType(.numberPad)
                                .multilineTextAlignment(.center)
                                .minimumScaleFactor(0.3).overlay(
                                    Rectangle()
                                        .frame(height: 1)
                                        .foregroundColor(Color.black)
                                        .padding([.top])
                                )
                                .cornerRadius(8).font(.system(size: 15))
                        }.padding([.leading,.trailing],30)
                        Divider()
                        HStack{
                            Text("收  购  人") .font(.system(size: 15))
                            Spacer()
                            TextField("收购人",text: $screenAgentName)
                                .multilineTextAlignment(.center)
                                .minimumScaleFactor(0.3).overlay(
                                    Rectangle()
                                        .frame(height: 1)
                                        .foregroundColor(Color.black)
                                        .padding([.top])
                                )
                                .cornerRadius(8).font(.system(size: 15))
                        }.padding([.leading,.trailing],30)
                        HStack {
                                Button(action:{
                                    isScreen = false
                                    screenName = ""
                                    screenPhone = ""
                                    screenAgentName = ""
                                    searchClient()
                                }) {
                                    Text("不筛选").padding().frame(
                                        maxWidth: .infinity,
                                        maxHeight:30,
                                        alignment: .center
                                    )
                                }
                                .overlay(
                                    RoundedRectangle(
                                        cornerRadius: 8
                                    )
                                    .stroke(
                                        Color.black,
                                        lineWidth: 0.5
                                    ) // 设置边框
                                ).edgesIgnoringSafeArea(
                                    .all
                                ) // 忽略安全区域，使视图覆盖整个屏幕
                                .cornerRadius(
                                    8
                                ) // 设置最大宽高为无穷，确保视图覆盖全屏
                                        
                                Button(action:{
                                    // Handle form submission
                                    searchClient()
                                }) {
                                    Text("查询").padding().frame(
                                        maxWidth: .infinity,
                                        maxHeight:30,
                                        alignment: .center
                                    )
                                       
                                }
                                .overlay(
                                    RoundedRectangle(
                                        cornerRadius: 8
                                    )
                                    .stroke(
                                        Color.black,
                                        lineWidth: 0.5
                                    ) // 设置边框
                                ).edgesIgnoringSafeArea(
                                    .all
                                ) // 忽略安全区域，使视图覆盖整个屏幕
                                .cornerRadius(
                                    8
                                ) // 设置最大宽高为无穷，确保视图覆盖全屏
                                        
                            }.padding([.leading,.trailing],30)
                    }
                }
                HStack{
                    Spacer()
                    Text("交易次数：\(client.count)")
                    Spacer()
                }.padding(5)
                Divider()
                ScrollView {
                    VStack(spacing: 20) {
                        // 使用 ForEach 遍历数组
                        ForEach(client, id: \.self) { item in
                            TranRecordCard(clientPojo: item,isProgressLoading:$isProgressLoading,totalPrice:$totalPrice,totalProduct:$totalProduct)
                                .frame(maxWidth:.infinity)
                                .background(Color("endColor"))
                                .overlay(
                                    RoundedRectangle(cornerRadius: 10)
                                        .stroke(
                                            Color.black,
                                            lineWidth: 0.5
                                        ) // 设置边框
                                ).edgesIgnoringSafeArea(
                                    .all
                                ) // 忽略安全区域，使视图覆盖整个屏幕
                                .cornerRadius(10) // 设置最大宽高为无穷，确保视图覆盖全屏
                                .padding([.leading,.trailing])
                        }
                    }
                }
                Divider()
                HStack{
                    Spacer()
                    Text("总件数：\(totalProduct)件")
                    Spacer()
                    Text("总价：\(totalPrice)元")
                    Spacer()
                }.padding(8)
                
            }.overlay(
                
                Group {
                    if isProgressLoading {
                        VStack {
                            ProgressView("正在导出,请稍等...")
                                .progressViewStyle(CircularProgressViewStyle())
                                .padding()
                                .background(Color.white)
                                .cornerRadius(10)
                                .shadow(radius: 10)
                                .frame(width: 200, height: 200)
                            
                        }
                    }
                }).fullScreenCover(isPresented: $exportRecord){
                    ExportRecordView(exportRecord:$exportRecord)
                }.fullScreenCover(isPresented: $navigateToDetail){
                    PdfViewer(fileName: $fileName,isPresented: $navigateToDetail)
                }
            .onAppear{
                mathSum()
            }.frame(maxWidth:.infinity,maxHeight: .infinity).background(
                // 创建渐变背景
                LinearGradient(
                    gradient: Gradient(
                        colors: [
                            Color("startColor").opacity(
                                10
                            ),
                            // 上半部分颜色，增加不透明度
                            Color("endColor").opacity(0.1)
                        ]// 上半部分颜色，增加不透明度
                    ),
                    startPoint: .top,
                    endPoint: .bottom
                )
                .edgesIgnoringSafeArea(.all)  // 确保背景覆盖整个屏幕
            ).navigationBarTitle("交易记录", displayMode: .inline) // 设置导航栏标题
                .navigationViewStyle(
                    StackNavigationViewStyle()
                ) // 推荐在全屏时使用此样式
                .background()
                .toolbar {
                    // 修改标题字体大小
                    ToolbarItem(placement: .topBarLeading) {
                     
                        Button(action: {       // 自定义返回动作
                            tranRecord = false
                            }) {
                                Image(systemName: "arrow.left.circle.fill") // 返回图标
                            }
                    }
                    ToolbarItem(placement: .navigationBarTrailing) {
                        // 使用 toolbarTitleMenu 创建下拉菜单
                        Menu {
                            Button("筛选") {
                                isScreen = true
                            }
                            Button("导出所有商品文件") {
                                isProgressLoading = true
                                exportFile()
                            }.alert("数据查询失败",isPresented: $exportFail){
                                Button("关闭",role: .cancel){
                                    exportFail = false
                                }
                            }
                            Button("查看导出记录") {
                                exportRecord = true
                            }
                        } label: {
                            // 设置菜单的图标
                            Image(systemName: "ellipsis").imageScale(.large)
                        }
                    }
                }
        }
      
    }
    func mathSum(){
          totalProduct = client.map(\.total_product).reduce(0,+)
          totalPrice = client.map(\.total_price).reduce(0,+)
      }
    
    func searchClient(){
        
        var nsPredicateArr:[NSPredicate] = []
        
        let predicateName: NSPredicate
        if !screenName.isEmpty{
            predicateName = NSPredicate(
                format: "name CONTAINS[c] %@",
                screenName
            )  // 模糊查询
            nsPredicateArr.append(predicateName)
        }
        
        let predicatePhone: NSPredicate
        if !screenPhone.isEmpty{
            predicatePhone = NSPredicate(
                format: "phone CONTAINS[c] %@",
                screenPhone
            )  // 模糊查询
            nsPredicateArr.append(predicatePhone)
        }
        
        let predicateAgentName: NSPredicate
        if !screenAgentName.isEmpty{
            predicateAgentName = NSPredicate(
                format: "agent_name CONTAINS[c] %@",
                screenAgentName
            )  // 模糊查询
            nsPredicateArr.append(predicateAgentName)
        }
        
        let predicate = NSCompoundPredicate(andPredicateWithSubpredicates: nsPredicateArr)
        
        
        client.nsPredicate = predicate
        //查询后重新计算总件数和总价
        mathSum()
    }
    
    
    @State private var fileName:String = ""
    @State private var productArrAll:[ProductPojo] = []
    
    /*
     导出所有商品文件
     */
    func exportFile(){
        let request: NSFetchRequest<Client> = Client.fetchRequest()
               // 设置查询条件，例如查询 amount > 10
        do{
            let clients = try viewContext.fetch(request)
            
            productArrAll.removeAll()
            
            for client in clients {
                
                if let clientID = client.id {
                    let requestProduct: NSFetchRequest<Product> = Product.fetchRequest()
                    requestProduct.predicate = NSPredicate(format: "pid = %@",clientID)
                    let products = try viewContext.fetch(requestProduct)
                    
                    
                    for object in products {
                        let productName : String = object.product_name ?? ""
                        let time : String = object.time ?? ""
                        let clientName : String = client.name ?? ""
                        let clientPhone : String = client.phone ?? ""
                        let clientAgentName : String = client.agent_name ?? ""
                        productArrAll.append(ProductPojo(product_name: productName,
                                                       product_price: String(object.product_price),
                                                         time: time,clientName:clientName,clientPhone:clientPhone,
                                                         clientAgentName:clientAgentName))
                    }
                    
                }
                
                
                
            }
        
            Task{
                
                fileName =   try await createPDF(product:productArrAll,
                                                 clientSignPath:"",
                                                 myFileName:fileName,
                                                 isSign: false)
              
                navigateToDetail = true
                isProgressLoading = false
                
              
                //保存导出信息
                saveExport()
                
            }
            
            
        }catch{
            exportFail = true
            isProgressLoading = false
        }
    }
    
    //保存签字确认单
    private func saveExport(){
        let export = Export(context:viewContext)
        export.id = UUID().uuidString
            .replacingOccurrences(of: "-", with: "")// 或者其他类型，确保是唯一的标识
        export.clientid = "dengpp"// 或者其他类型，确保是唯一的标识
        export.exportFilePath = fileName
        export.exportDate = formattedDate()
        do{
            try viewContext.save()
        }catch{
            print("Error saving context: \(error.localizedDescription)")
        }
    }
    // 创建日期格式化器
    func formattedDate() -> String {
        let formatter = DateFormatter()
        // 获取当前时间
        let currentDate = Date()
        formatter.dateStyle = .long
        formatter.timeStyle = .medium
        return formatter.string(from: currentDate)
    }

}
